<template>
  <div class="flex flex-col md:flex-row min-h-screen animate-fade-in">
    <!-- 左侧宣传区 -->
    <div 
      class="md:w-1/2 bg-gradient-to-br from-primary/80 to-accent/80 text-white p-8 md:p-16 flex flex-col justify-center relative overflow-hidden"
      :style="{ backgroundImage: 'url(/src/assets/images/background.png)', backgroundSize: 'cover', backgroundPosition: 'center', backgroundBlendMode: 'overlay' }"
    >
      <!-- 装饰元素 -->
      <div class="absolute top-0 right-0 w-64 h-64 bg-white/5 rounded-full -mr-32 -mt-32 blur-2xl"></div>
      <div class="absolute bottom-0 left-0 w-96 h-96 bg-white/5 rounded-full -ml-48 -mb-48 blur-3xl"></div>
      
      <div class="relative z-10 max-w-lg mx-auto animate-slide-up">
        <div class="mb-12">
          <h3 class="text-[clamp(1.5rem,3vw,2.4rem)] font-bold leading-tight mb-4 text-shadow">
            加入书香世界，开启阅读之旅
          </h3>
          <p class="text-[clamp(1rem,2vw,1.25rem)] text-white/90 mb-8">
            注册成为会员，享受更多专属福利
          </p>
          
          <!-- 功能模块 -->
          <div class="grid grid-cols-1 gap-4 mt-8">
            <div 
              v-for="(benefit, index) in benefits" 
              :key="index"
              class="glass-effect p-4 rounded-xl flex items-center transform hover:scale-[1.01] transition-custom"
              :style="{ animationDelay: `${index * 0.1}s` }"
            >
              <div class="flex-shrink-0">
                <div class="w-12 h-12 bg-white/30 rounded-full flex items-center justify-center">
                  <i :class="benefit.icon + ' text-2xl'"></i>
                </div>
              </div>
              <div class="ml-4 text-left">
                <h3 class="font-bold text-base mb-1">{{ benefit.title }}</h3>
                <p class="text-sm text-white/80">{{ benefit.description }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 右侧注册区 -->
    <div class="md:w-1/2 flex items-center justify-center p-8 md:p-16 bg-white min-h-screen md:min-h-0">
      <div class="w-full max-w-md mx-auto animate-bounce-in">
        <!-- 标题区域 -->
        <div class="text-center mb-10">
          <h1 class="text-3xl font-bold text-gray-800 mb-4">
            创建账号✨
          </h1>
          <p class="text-gray-500 text-base">填写信息，开启您的阅读之旅</p>
        </div>
        
        <!-- 注册表单 -->
        <div class="space-y-5">
          <!-- 用户名输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              用户名
            </label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                <i class="fas fa-user text-gray-400 text-sm"></i>
              </div>
              <input
                v-model="registerForm.username"
                type="text"
                placeholder="请输入用户名"
                :class="[
                  'w-full pl-12 pr-4 py-4 border rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all duration-300 text-gray-700 placeholder-gray-400',
                  errors.username ? 'border-red-300 focus:border-red-500 focus:ring-red-200' : 'border-gray-200'
                ]"
                @input="errors.username = ''"
                @blur="checkUsername"
              />
            </div>
            <p v-if="errors.username" class="text-red-500 text-xs mt-1">{{ errors.username }}</p>
          </div>
          
          <!-- 邮箱输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              电子邮箱
            </label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                <i class="fas fa-envelope text-gray-400 text-sm"></i>
              </div>
              <input
                v-model="registerForm.email"
                type="email"
                placeholder="请输入邮箱地址"
                :class="[
                  'w-full pl-12 pr-4 py-4 border rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all duration-300 text-gray-700 placeholder-gray-400',
                  errors.email ? 'border-red-300 focus:border-red-500 focus:ring-red-200' : 'border-gray-200'
                ]"
                @input="errors.email = ''"
                @blur="checkEmail"
              />
            </div>
            <p v-if="errors.email" class="text-red-500 text-xs mt-1">{{ errors.email }}</p>
          </div>
          
          <!-- 手机号输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              手机号码
            </label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                <i class="fas fa-mobile-alt text-gray-400 text-sm"></i>
              </div>
              <input
                v-model="registerForm.phone"
                type="tel"
                placeholder="请输入11位手机号"
                maxlength="11"
                :class="[
                  'w-full pl-12 pr-4 py-4 border rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all duration-300 text-gray-700 placeholder-gray-400',
                  errors.phone ? 'border-red-300 focus:border-red-500 focus:ring-red-200' : 'border-gray-200'
                ]"
                @input="errors.phone = ''"
                @blur="checkPhone"
              />
            </div>
            <p v-if="errors.phone" class="text-red-500 text-xs mt-1">{{ errors.phone }}</p>
          </div>
          
          <!-- 密码输入 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              密码
            </label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                <i class="fas fa-lock text-gray-400 text-sm"></i>
              </div>
              <input
                v-model="registerForm.password"
                :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码"
                :class="[
                  'w-full pl-12 pr-12 py-4 border rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all duration-300 text-gray-700 placeholder-gray-400',
                  errors.password ? 'border-red-300 focus:border-red-500 focus:ring-red-200' : 'border-gray-200'
                ]"
                @input="errors.password = ''; checkPasswordStrength()"
              />
              <button
                type="button"
                @click="togglePassword"
                class="absolute inset-y-0 right-0 pr-4 flex items-center text-gray-400 hover:text-primary transition-colors"
              >
                <i :class="showPassword ? 'fas fa-eye' : 'fas fa-eye-slash'" class="text-sm"></i>
              </button>
            </div>
            <p v-if="errors.password" class="text-red-500 text-xs mt-1">{{ errors.password }}</p>
          </div>
          
          <!-- 确认密码 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              确认密码
            </label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                <i class="fas fa-lock text-gray-400 text-sm"></i>
              </div>
              <input
                v-model="registerForm.confirmPassword"
                :type="showConfirmPassword ? 'text' : 'password'"
                placeholder="请再次输入密码"
                :class="[
                  'w-full pl-12 pr-12 py-4 border rounded-lg focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all duration-300 text-gray-700 placeholder-gray-400',
                  errors.confirmPassword ? 'border-red-300 focus:border-red-500 focus:ring-red-200' : 'border-gray-200'
                ]"
                @input="errors.confirmPassword = ''"
              />
              <button
                type="button"
                @click="toggleConfirmPassword"
                class="absolute inset-y-0 right-0 pr-4 flex items-center text-gray-400 hover:text-primary transition-colors"
              >
                <i :class="showConfirmPassword ? 'fas fa-eye' : 'fas fa-eye-slash'" class="text-sm"></i>
              </button>
            </div>
            <p v-if="errors.confirmPassword" class="text-red-500 text-xs mt-1">{{ errors.confirmPassword }}</p>
          </div>
          
          <!-- 用户类型选择 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-3">账号类型</label>
            <div class="grid grid-cols-2 gap-4">
              <label
                v-for="type in userTypes"
                :key="type.value"
                class="relative cursor-pointer"
              >
                <input
                  v-model="registerForm.userType"
                  :value="type.value"
                  type="radio"
                  class="sr-only"
                >
                <div
                  class="flex items-center justify-center py-4 px-6 border-2 rounded-lg transition-all duration-300 text-sm font-medium"
                  :class="registerForm.userType === type.value
                    ? 'border-primary bg-primary/5 text-primary'
                    : 'border-gray-200 text-gray-600 hover:border-primary/50 hover:bg-primary/5'"
                >
                  <i :class="type.icon + ' mr-2 text-sm'"></i>
                  <span>{{ type.label }}</span>
                </div>
              </label>
            </div>
          </div>

          <!-- 注册按钮 -->
          <button
            type="button"
            @click="handleRegister"
            :disabled="loading"
            class="w-full bg-primary hover:bg-accent text-white font-medium py-4 rounded-lg transition-all duration-300 transform hover:-translate-y-0.5 hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none mb-6"
          >
            {{ loading ? '注册中...' : '立即注册' }}
          </button>

          <!-- 登录链接 -->
          <div class="text-center text-gray-500 text-sm">
            <span>已有账号? </span>
            <router-link
              to="/login"
              class="text-primary hover:text-accent font-medium transition-colors"
            >
              返回登录
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)
const passwordStrength = ref(0)
const errors = ref({})

// 表单数据
const registerForm = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  userType: 'user'
})

// 表单验证函数
const validateForm = () => {
  errors.value = {}
  let isValid = true

  // 验证用户名
  if (!registerForm.username) {
    errors.value.username = '请输入用户名'
    isValid = false
  } else if (registerForm.username.length < 3 || registerForm.username.length > 20) {
    errors.value.username = '用户名长度在 3 到 20 个字符'
    isValid = false
  } else if (!/^[a-zA-Z0-9_]+$/.test(registerForm.username)) {
    errors.value.username = '用户名只能包含字母、数字和下划线'
    isValid = false
  }

  // 验证邮箱
  if (!registerForm.email) {
    errors.value.email = '请输入邮箱地址'
    isValid = false
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) {
    errors.value.email = '请输入正确的邮箱格式'
    isValid = false
  }

  // 验证手机号
  if (!registerForm.phone) {
    errors.value.phone = '请输入手机号码'
    isValid = false
  } else if (!/^1[3-9]\d{9}$/.test(registerForm.phone)) {
    errors.value.phone = '请输入正确的手机号码'
    isValid = false
  }

  // 验证密码
  if (!registerForm.password) {
    errors.value.password = '请输入密码'
    isValid = false
  } else if (registerForm.password.length < 6 || registerForm.password.length > 20) {
    errors.value.password = '密码长度在 6 到 20 个字符'
    isValid = false
  } else if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{6,}$/.test(registerForm.password)) {
    errors.value.password = '密码必须包含字母和数字'
    isValid = false
  }

  // 验证确认密码
  if (!registerForm.confirmPassword) {
    errors.value.confirmPassword = '请确认密码'
    isValid = false
  } else if (registerForm.confirmPassword !== registerForm.password) {
    errors.value.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }



  return isValid
}

// 密码强度检查
const checkPasswordStrength = () => {
  const password = registerForm.password
  if (!password) {
    passwordStrength.value = 0
    return
  }

  let strength = 0
  if (password.length >= 8) strength++
  if (/[a-z]/.test(password)) strength++
  if (/[A-Z]/.test(password)) strength++
  if (/\d/.test(password)) strength++
  if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++

  passwordStrength.value = Math.min(strength, 4)
}

// 用户类型选项
const userTypes = [
  { value: 'user', label: '个人用户', icon: 'fas fa-user' },
  { value: 'merchant', label: '商家入驻', icon: 'fas fa-store' }
]

// 注册福利
const benefits = [
  {
    icon: 'fas fa-gift',
    title: '新人好礼',
    description: '注册即送50元优惠券'
  },
  {
    icon: 'fas fa-tags',
    title: '会员折扣',
    description: '全场图书享95折优惠'
  },
  {
    icon: 'fas fa-bookmark',
    title: '收藏书单',
    description: '创建个性化阅读书单'
  }
]

// 密码强度计算
const passwordStrengthText = computed(() => {
  switch (passwordStrength.value) {
    case 0: return '请输入密码'
    case 1: return '密码强度：弱'
    case 2: return '密码强度：中等'
    case 3: return '密码强度：强'
    case 4: return '密码强度：很强'
    default: return ''
  }
})

const passwordStrengthTextClass = computed(() => {
  switch (passwordStrength.value) {
    case 0: return 'text-gray-400'
    case 1: return 'text-red-500'
    case 2: return 'text-yellow-500'
    case 3: return 'text-blue-500'
    case 4: return 'text-green-500'
    default: return 'text-gray-400'
  }
})

// 密码强度颜色
const getPasswordStrengthColor = (index) => {
  if (index <= passwordStrength.value) {
    switch (passwordStrength.value) {
      case 1: return 'bg-red-500'
      case 2: return 'bg-yellow-500'
      case 3: return 'bg-blue-500'
      case 4: return 'bg-green-500'
      default: return 'bg-gray-200'
    }
  }
  return 'bg-gray-200'
}



// 切换密码显示
const togglePassword = () => {
  showPassword.value = !showPassword.value
}

// 切换确认密码显示
const toggleConfirmPassword = () => {
  showConfirmPassword.value = !showConfirmPassword.value
}

// 检查用户名是否可用
const checkUsername = async () => {
  if (!registerForm.username) return

  // 这里应该调用API检查用户名是否已存在
  // TODO: 实现用户名检查API调用
}

// 检查邮箱是否可用
const checkEmail = async () => {
  if (!registerForm.email) return

  // 这里应该调用API检查邮箱是否已存在
  // TODO: 实现邮箱检查API调用
}

// 检查手机号是否可用
const checkPhone = async () => {
  if (!registerForm.phone) return

  // 这里应该调用API检查手机号是否已存在
  // TODO: 实现手机号检查API调用
}

// 处理注册
const handleRegister = async () => {
  // 验证表单
  if (!validateForm()) {
    ElMessage.error('请检查输入信息')
    return
  }

  try {
    loading.value = true

    // 调用用户store的注册方法
    await userStore.register(registerForm)

    ElMessage.success('注册成功！即将跳转到登录页面')

    // 注册成功后跳转到登录页
    setTimeout(() => {
      router.push('/login')
    }, 1500)

  } catch (error) {
    console.error('注册失败:', error)
    // 显示具体的错误信息
    const errorMessage = error.message || '注册失败，请稍后重试'
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}



// 页面加载时的动画效果
onMounted(() => {
  // 添加页面加载动画
  const elements = document.querySelectorAll('.animate-slide-up, .animate-bounce-in')
  elements.forEach((el, index) => {
    el.style.animationDelay = `${index * 0.1}s`
  })
})
</script>

<style scoped>
/* 输入框样式 */
input:focus {
  outline: none;
}

/* 按钮样式 */
button:disabled {
  transform: none !important;
}

/* 无障碍访问性优化 */
.sr-only {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .glass-effect {
    backdrop-filter: blur(5px);
  }

  .grid-cols-2 {
    grid-template-columns: 1fr;
    gap: 0.75rem;
  }
}

/* 动画优化 */
@media (prefers-reduced-motion: reduce) {
  .animate-fade-in,
  .animate-slide-up,
  .animate-bounce-in,
  .transition-all,
  .transition-colors {
    animation: none;
    transition: none;
  }
}
</style>
